import { defineStore } from "pinia";
import { db } from "../db";
import { ConversationProps } from "../types";

export interface ConversationStore {
  items: ConversationProps[];
  selectedId: number;
}

export const useConversationStore = defineStore("conversation", {
  state: (): ConversationStore => {
    return {
      items: [],
      selectedId: -1,
    };
  },
  actions: {
    // 从本地存储中查询出会话列表
    async fetchConversations() {
      const items = await db.conversations.orderBy('updatedAt') // 按更新日期排序
        .reverse() // 倒序排列
        .toArray(); // 转换为数组
      this.items = items;
    },
    async createConversation(createdData: Omit<ConversationProps, "id">) {
      // 本地存储中新增会话
      const newCId = await db.conversations.add(createdData);
      //   pinia 中新增会话
      this.items.unshift({
        id: newCId,
        ...createdData,
      });
      //   返回新增会话的id
      return newCId;
    },
    async deleteConversation(id: number) {
      // 本地存储中删除会话
      await db.conversations.delete(id);
      //   pinia 中删除会话
      const index = this.items.findIndex((item) => item.id === id);
      if (index > -1) {
        this.items.splice(index, 1);
      }
    },
    async updateConversation(id: number, newData: Omit<ConversationProps, "id">) {
      // 本地存储中更新会话
      await db.conversations.update(id, newData);
      //   pinia 中更新会话
      const index = this.items.findIndex((item) => item.id === id);
      if (index > -1) {
        this.items[index] = { id, ...newData };
      }
    },
  },
  getters: {
    // 根据会话id，从 pinia 的会话列表中筛选出目标会话
    getConversationById: (state) => (id: number) => {
      return state.items.find((item) => item.id === id);
    },
  },
});
